﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Accout;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.CommandHandler.Account
{
    public class DelAccountHandler : IRequestHandler<DelAccountCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accRepo;
        private readonly IMapper mapper;
        private readonly ILogger<DelAccountHandler> logger;

        /// <summary>
        /// 通过构造函数注入所需的资源
        /// </summary>
        /// <param name="accRepo">账号仓储</param>
        /// <param name="mapper">automapper 工具</param>
        /// <param name="logger">日志工具</param>
        public DelAccountHandler(IBaseRepository<AccountModel> accRepo,IMapper mapper,ILogger<DelAccountHandler> logger)
        {
            this.accRepo = accRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 中介者处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(DelAccountCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            //根据账号id查找model
            var model = accRepo.GetModel(request.Id);
            if (model == null) {
                result.Data = 0;
                result.Msg = "错误.您要删除的账号不存在!";
                result.Code = ApiEnums.Error;
                return Task.FromResult(result);
            }
             
            model.IsDeleted = true;
           
            var r = accRepo.Update(model);

            if (r > 0)
            {
                result.Data = r;
                result.Msg = "更新管理员成功!!";
                result.Code = ApiEnums.Success;
            }
            else {
                result.Data = r;
                result.Msg = "更新管理员失败!!";
                result.Code = ApiEnums.Fail;
            }
            return Task.FromResult(result);
        }
    }
}
